package chat;

import org.junit.Test;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * URL(Uniform Resource Locator):统一资源定位符 (种子)
 * <p>
 * 一个具体的URL就对应着互联网上某一资源的地址
 * <p>
 * URL格式
 * http:/127.0.0.1:8080/examples/abc.jpg?name=Tom
 * 应用层协议 ip    port   资源地址         参数列表
 */
public class URLTest {
    @Test
    public void testURL() {
        String str = "https://javaguide.cn/home.html";
        try {
            URL url = new URL(str);
            System.out.println(url.getProtocol()); // 协议名
            System.out.println(url.getHost());
            System.out.println(url.getPort());
            System.out.println(url.getPath());
            System.out.println(url.getFile());
        } catch (MalformedURLException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 将URL代表的资源下载到本地
     */
    @Test
    public void testDownload() {
        String str = "https://javaguide.cn/home.html";
        try {
            URL url = new URL(str);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            InputStream inputStream = urlConnection.getInputStream();
            FileOutputStream fileOutputStream = new FileOutputStream("Download.html");
            byte[] bytes = new byte[1024];
            int len;
            while ((len = inputStream.read(bytes)) != -1) {
                fileOutputStream.write(bytes, 0, len);
            }

            fileOutputStream.close();
            inputStream.close();
            urlConnection.disconnect();

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
